#include "friendsessionarea.h"
#include "Data.h"
#include "Logger.h"

#include <QVBoxLayout>
#include <QPushButton>
#include <QGridLayout>
#include <QScrollBar>
#include <QStyleOption>
#include <QPainter>

using namespace model;

#define TEST_SCROLL 1

FriendSessionArea::FriendSessionArea(QWidget *parent)
    : QScrollArea {parent}
{
    // 1. 设置相关属性
    this->setWidgetResizable(true);
    this->verticalScrollBar()->setStyleSheet(R"(
        QScrollBar:vertical {
            width: 6px;
            background-color: rgb(50, 50, 50);
            border-radius: 3px;
        }
        QScrollBar::handle:vertical {
            background-color: rgb(160, 160, 160);
            min-height: 20px;
            border-radius: 3px;
        }
    )");
    this->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px; }");
    this->setStyleSheet("QWidget { border: none; background-color: rgb(240, 240, 240); }");

    // 2. 创建container
    container = new QWidget();
    container->setFixedWidth(320);  // 设置稍微宽一点的宽度，更好布局
    this->setWidget(container);

    QVBoxLayout* layout = new QVBoxLayout();
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    layout->setAlignment(Qt::AlignTop);
    container->setLayout(layout);
    container->setVisible(true);

#if TEST
    for (int i = 0; i < 50; ++i) {
        QPushButton* btn = new QPushButton("测试按钮");
        btn->setStyleSheet(R"(
            QPushButton {
                background-color: rgb(245, 245, 245);
                border: 1px solid rgb(220, 220, 220);
                border-radius: 5px;
                height: 40px;
                font-size: 16px;
                color: rgb(50, 50, 50);
            }
            QPushButton:hover {
                background-color: rgb(230, 230, 230);
            }
        )");
        layout->addWidget(btn);
    }
#else
    QIcon icon(":/res/image/default_avatar.png");
    if (icon.isNull()) {
        qDebug() << "图标加载失败！";
    }
    for (int i = 0; i < 30; ++i) {
        this->addItem(FriendItemType, QString::number(i), icon, QString("会话 %1").arg(i), QString("最新消息 %1").arg(i));
    }
#endif
}

void FriendSessionArea::addItem(const ItemType &type, const QString &id, const QIcon &avatar, const QString &name, const QString &text)
{
    FriendSessionItem* item = nullptr;

    switch (type) {
    case SessionItemType:
        qDebug() << "Creating SessionItem";
        item = new SessionItem(this, id, name, avatar, text); // Ensure text is passed
        break;
    case FriendItemType:
        qDebug() << "Creating FriendItem";
        item = new FriendItem(this, id, name, avatar, text); // Ensure text is passed
        break;
    case ApplyItemType:
        qDebug() << "Creating ApplyItem";
        item = new ApplyItem(this, id, name, avatar); // No text used here as per current design
        break;
    default:
        qWarning() << "Unknown ItemType";
        return;
    }

    container->layout()->addWidget(item);
}



void FriendSessionArea::clear()
{
    QLayout* layout = container->layout();
    // 遍历布局管理器的所以元素
    for(int i = layout->count() - 1; i >= 0; --i) {
        QLayoutItem* item = layout->takeAt(i); // 移除
        if(item->widget()) // 释放
        {
            delete item->widget();
        }
    }
}

FriendSessionItem::FriendSessionItem(QWidget *owner, const QIcon &avatar, const QString &name, const QString &text)
    : owner(owner)
{
    // 设置样式
    this->setFixedHeight(70);
    this->setStyleSheet(R"(
        QWidget {
            background-color: rgb(255, 255, 255);
            border-bottom: 1px solid rgb(220, 220, 220);
        }
        // QWidget:hover {
        //     background-color: rgb(245, 245, 245);
        // }
    )");

    // 创建网格布局管理器
    QGridLayout* layout = new QGridLayout();
    layout->setContentsMargins(15, 5, 15, 5);
    layout->setHorizontalSpacing(10);
    layout->setVerticalSpacing(0);

    // 创建头像
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(50, 50);
    avatarBtn->setIconSize(QSize(50, 50));
    avatarBtn->setIcon(avatar);
    avatarBtn->setStyleSheet("QPushButton {border: none; border-radius: 25px;}"); // 圆形头像
    avatarBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    // 创建名字
    QLabel* nameLabel = new QLabel(name);
    nameLabel->setStyleSheet(R"(
        QLabel {
            font-size: 16px;
            font-weight: bold;
            color: rgb(30, 30, 30);
        }
    )");
    nameLabel->setFixedHeight(30);
    nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 创建消息预览
    message_label = new QLabel(text);
    message_label->setStyleSheet(R"(
        QLabel {
            font-size: 14px;
            color: rgb(100, 100, 100);
        }
    )");
    message_label->setFixedHeight(30);
    message_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 添加控件到布局
    layout->addWidget(avatarBtn, 0, 0, 2, 2);
    layout->addWidget(nameLabel, 0, 2, 1, 8);
    layout->addWidget(message_label, 1, 2, 1, 8);

    this->setLayout(layout);
}


void FriendSessionItem::paintEvent(QPaintEvent *event)
{
    (void) event;
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void FriendSessionItem::mousePressEvent(QMouseEvent *event)
{
    (void) event;
    select();
}

void FriendSessionItem::enterEvent(QEnterEvent *event)
{
    (void) event;
    // 当前item为选中状态，不做操作
    if(this->selected) {
        return;
    }
    // 非选中
    this->setStyleSheet("QWidget { background-color: rgb(215, 215, 215);}");
}

void FriendSessionItem::leaveEvent(QEvent *event)
{
    (void) event;

    // 选中状态
    if (this->selected) {
        return;
    }
    // 还原背景色
    this->setStyleSheet("QWidget { background-color: rgb(231, 231, 231);}");
}

void FriendSessionItem::select()
{
    // 鼠标点击触发
    // 获取所有兄弟元素
    const QObjectList childs = this->parentWidget()->children();
    for(QObject* child : childs)
    {
        if(!child->isWidgetType())
            continue; // 只要widget

        FriendSessionItem* item = dynamic_cast<FriendSessionItem*>(child);
        if(item->selected) {
            item->selected = false;
            item->setStyleSheet("QWidget { background-color: rgb(231, 231, 231); }");
        }
    }
    // 设置当前 item 背景色, 还原其他元素的背景色.
    this->setStyleSheet("QWidget { background-color: rgb(210, 210, 210); }");
    this->selected = true;

    this->active();
}


void FriendSessionItem::active()
{
    // 不执行任何逻辑
}

SessionItem::SessionItem(QWidget *owner, const QString &sessionId, const QString &name, const QIcon &avatar, const QString &lastMessage)
    :FriendSessionItem(owner, avatar, name, lastMessage), session_id(sessionId), last_message(lastMessage)
{
    // 处理最后一个消息
}

void SessionItem::active()
{
    LOG_DEBUG() << "点击了SessionItem触发的逻辑，SessionId=" << session_id;

    // 记载会话历史消息
}

FriendItem::FriendItem(QWidget *owner, const QString &userId, const QString &name, const QIcon &avatar, const QString &description)
    :  FriendSessionItem(owner, avatar, name, description), user_id(userId)
{

}

void FriendItem::active()
{

}

ApplyItem::ApplyItem(QWidget *owner, const QString &userId, const QString &name, const QIcon &avatar)
    : FriendSessionItem(owner, avatar, name, ""), user_id(userId)
{
    // 获取父类的布局并移除消息标签
    QGridLayout* layout = dynamic_cast<QGridLayout*>(this->layout());
    layout->removeWidget(message_label);
    delete message_label;  // 释放内存

    // 创建按钮
    QPushButton* acceptBtn = new QPushButton("同意");
    QPushButton* rejectBtn = new QPushButton("拒绝");

    // 设置按钮样式
    acceptBtn->setStyleSheet(R"(
        QPushButton {
            background-color: #4CAF50;  /* 绿色背景 */
            color: white;                /* 白色字体 */
            border: none;
            border-radius: 5px;
            padding: 8px 12px;
            font-size: 12px;
        }
        QPushButton:hover {
            background-color: #45a049;  /* 悬停时稍微深色 */
        }
    )");

    rejectBtn->setStyleSheet(R"(
        QPushButton {
            background-color: #f44336;  /* 红色背景 */
            color: white;                /* 白色字体 */
            border: none;
            border-radius: 5px;
            padding: 8px 12px;
            font-size: 12px;
        }
        QPushButton:hover {
            background-color: #e53935;  /* 悬停时稍微深色 */
        }
    )");

    // 将按钮添加到布局
    layout->addWidget(acceptBtn, 1, 2, 1, 1);
    layout->addWidget(rejectBtn, 1, 3, 1, 1);
}

void ApplyItem::active()
{
    LOG_DEBUG() << "点击了ApplyItem, userId=" << user_id;
}
